import React, { useState, useEffect } from 'react';
import {
  Table,
  Button,
  Modal,
  Form,
  Input,
  message,
  Popconfirm,
  Space,
  Card,
  Tag,
  ColorPicker
} from 'antd';
import {
  PlusOutlined,
  EditOutlined,
  DeleteOutlined
} from '@ant-design/icons';
import { adminApi } from '../../services/api';

const TagManagement = () => {
  const [tags, setTags] = useState([]);
  const [loading, setLoading] = useState(false);
  const [modalVisible, setModalVisible] = useState(false);
  const [editingTag, setEditingTag] = useState(null);
  const [form] = Form.useForm();
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
    total: 0,
  });

  // 预设颜色选项
  const presetColors = [
    '#f50', '#2db7f5', '#87d068', '#108ee9',
    '#f56a00', '#722ed1', '#eb2f96', '#52c41a',
    '#13c2c2', '#1890ff', '#faad14', '#a0d911'
  ];

  useEffect(() => {
    loadTags();
  }, []);

  const loadTags = async (page = 1, size = 10) => {
    setLoading(true);
    try {
      const response = await adminApi.tags.list({ page, size });
      setTags(response.data?.records || []);
      setPagination({
        current: page,
        pageSize: size,
        total: response.data?.total || 0,
      });
    } catch (error) {
      console.error('加载标签失败:', error);
    } finally {
      setLoading(false);
    }
  };

  const handleTableChange = (pagination) => {
    loadTags(pagination.current, pagination.pageSize);
  };

  const showModal = (tag = null) => {
    setEditingTag(tag);
    setModalVisible(true);
    if (tag) {
      form.setFieldsValue(tag);
    } else {
      form.resetFields();
      // 设置默认颜色
      form.setFieldsValue({ color: '#1890ff' });
    }
  };

  const handleSubmit = async (values) => {
    try {
      // 确保颜色值是字符串格式
      const submitData = {
        ...values,
        color: typeof values.color === 'string' ? values.color : values.color.toHexString()
      };

      if (editingTag) {
        await adminApi.tags.update(editingTag.id, submitData);
        message.success('更新标签成功');
      } else {
        await adminApi.tags.create(submitData);
        message.success('创建标签成功');
      }
      
      setModalVisible(false);
      loadTags(pagination.current, pagination.pageSize);
    } catch (error) {
      console.error('保存标签失败:', error);
    }
  };

  const handleDelete = async (id) => {
    try {
      await adminApi.tags.delete(id);
      message.success('删除标签成功');
      loadTags(pagination.current, pagination.pageSize);
    } catch (error) {
      console.error('删除标签失败:', error);
    }
  };

  const columns = [
    {
      title: 'ID',
      dataIndex: 'id',
      key: 'id',
      width: 80,
    },
    {
      title: '标签名称',
      dataIndex: 'name',
      key: 'name',
    },
    {
      title: '颜色',
      dataIndex: 'color',
      key: 'color',
      width: 120,
      render: (color, record) => (
        <Tag color={color}>{record.name}</Tag>
      ),
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      key: 'createTime',
      render: (time) => new Date(time).toLocaleString(),
    },
    {
      title: '更新时间',
      dataIndex: 'updateTime',
      key: 'updateTime',
      render: (time) => new Date(time).toLocaleString(),
    },
    {
      title: '操作',
      key: 'action',
      width: 200,
      render: (_, record) => (
        <Space>
          <Button
            type="link"
            icon={<EditOutlined />}
            onClick={() => showModal(record)}
          >
            编辑
          </Button>
          <Popconfirm
            title="确定要删除这个标签吗？"
            description="删除标签可能会影响相关菜品"
            onConfirm={() => handleDelete(record.id)}
            okText="确定"
            cancelText="取消"
          >
            <Button type="link" danger icon={<DeleteOutlined />}>
              删除
            </Button>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  return (
    <div style={{ 
      padding: window.innerWidth <= 768 ? '16px' : '24px',
      background: '#f8f9fa',
      minHeight: '100vh'
    }}>
      <Card 
        style={{ 
          border: 'none',
          boxShadow: '0 2px 8px rgba(0,0,0,0.04)',
          borderRadius: '12px'
        }}
        bodyStyle={{ padding: window.innerWidth <= 768 ? '16px' : '24px' }}
      >
        <div style={{ 
          display: 'flex', 
          justifyContent: 'space-between', 
          alignItems: 'center', 
          marginBottom: 20,
          flexWrap: window.innerWidth <= 768 ? 'wrap' : 'nowrap',
          gap: 12
        }}>
          <h1 style={{ 
            margin: 0, 
            fontSize: window.innerWidth <= 768 ? '20px' : '24px',
            fontWeight: 600,
            color: '#1a1a1a'
          }}>
            标签管理
          </h1>
          <Button
            type="primary"
            icon={<PlusOutlined />}
            onClick={() => showModal()}
            style={{
              borderRadius: '8px',
              fontWeight: 500,
              height: window.innerWidth <= 768 ? '36px' : '40px',
              padding: window.innerWidth <= 768 ? '0 16px' : '0 20px'
            }}
          >
            新增标签
          </Button>
        </div>

        <Table
          columns={columns}
          dataSource={tags}
          rowKey="id"
          loading={loading}
          pagination={{
            ...pagination,
            showSizeChanger: window.innerWidth > 768,
            showQuickJumper: window.innerWidth > 768,
            showTotal: (total, range) => (
              <span style={{ fontSize: '13px', color: '#666' }}>
                共 {total} 条
              </span>
            ),
            size: window.innerWidth <= 768 ? 'small' : 'default',
            style: { marginTop: 16 }
          }}
          onChange={handleTableChange}
          style={{ 
            borderRadius: '8px',
            overflow: 'hidden'
          }}
        />
      </Card>

      <Modal
        title={editingTag ? '编辑标签' : '新增标签'}
        open={modalVisible}
        onCancel={() => setModalVisible(false)}
        footer={null}
        width={window.innerWidth <= 768 ? '95%' : 500}
        style={{ 
          top: window.innerWidth <= 768 ? 20 : undefined,
          maxHeight: window.innerWidth <= 768 ? '90vh' : undefined
        }}
        bodyStyle={{ 
          padding: window.innerWidth <= 768 ? '16px' : '24px',
          maxHeight: window.innerWidth <= 768 ? 'calc(90vh - 110px)' : undefined,
          overflowY: 'auto'
        }}
      >
        <Form
          form={form}
          layout="vertical"
          onFinish={handleSubmit}
          size={window.innerWidth <= 768 ? 'middle' : 'large'}
        >
          <Form.Item
            name="name"
            label="标签名称"
            rules={[
              { required: true, message: '请输入标签名称' },
              { max: 20, message: '标签名称不能超过20个字符' }
            ]}
          >
            <Input placeholder="请输入标签名称" />
          </Form.Item>

          <Form.Item
            name="color"
            label="标签颜色"
            rules={[{ required: true, message: '请选择标签颜色' }]}
          >
            <div>
              <ColorPicker
                presets={[
                  {
                    label: '推荐颜色',
                    colors: presetColors,
                  },
                ]}
                showText
                onChange={(color) => {
                  form.setFieldsValue({ color: color.toHexString() });
                }}
                size={window.innerWidth <= 768 ? 'small' : 'middle'}
              />
              <div style={{ marginTop: 12 }}>
                <span style={{ fontSize: window.innerWidth <= 768 ? '13px' : '14px' }}>预览：</span>
                <Tag 
                  color={form.getFieldValue('color')}
                  style={{ fontSize: window.innerWidth <= 768 ? '12px' : '14px' }}
                >
                  {form.getFieldValue('name') || '标签预览'}
                </Tag>
              </div>
            </div>
          </Form.Item>

          <Form.Item style={{ marginBottom: 0 }}>
            <div style={{ 
              display: 'flex', 
              gap: 12,
              justifyContent: 'flex-end',
              flexWrap: 'wrap'
            }}>
              <Button 
                type="primary" 
                htmlType="submit"
                style={{
                  borderRadius: '8px',
                  fontWeight: 500,
                  minWidth: window.innerWidth <= 768 ? '80px' : '100px'
                }}
              >
                {editingTag ? '更新' : '创建'}
              </Button>
              <Button 
                onClick={() => setModalVisible(false)}
                style={{
                  borderRadius: '8px',
                  fontWeight: 500
                }}
              >
                取消
              </Button>
            </div>
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default TagManagement;